﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;
using System.Web.UI.HtmlControls;

public partial class Property_Info_Appraisals : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SetAppraisalTable();
        SetMediaTable();
        if (!Request.IsAuthenticated)
        {
            TabContainer1.Visible = false;
        }
        else
        {
            TabContainer1.Enabled = true;
            TabContainer1.Visible = true;
        }
    }

    private void SetAppraisalTable()
    {
        SqlConnection cn = new SqlConnection(YAF.Classes.Config.ConnectionString);
        cn.Open();

        SqlCommand cmd = new SqlCommand("social_appraisals_list", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader dr = cmd.ExecuteReader();

        appraisals.Text = "";

        bool af = false;
        while (dr.Read())
        {
            af = true;
            decimal val = Convert.ToDecimal(dr[2].ToString());
            DateTime date = Convert.ToDateTime(dr[3].ToString());
            string file = "../upload/appraisals/" + dr[1].ToString() + dr[0].ToString();

            appraisals.Text += "<tr><td>";
            appraisals.Text += "<a href=";
            appraisals.Text += file;
            appraisals.Text += ">appraisal.pdf</a>";
            appraisals.Text += "</td><td>$";
            appraisals.Text += String.Format("{0:0,0}", val);
            appraisals.Text += "</td><td>";
            appraisals.Text += date.ToShortDateString();
            appraisals.Text += "</td></tr>";
        }
        if (af == false) appraisals.Text += "<tr><td>No appraisals available.</td></td><td></td><td></tr>";
        
    }

    private void SetMediaTable()
    {
        SqlConnection cn = new SqlConnection(YAF.Classes.Config.ConnectionString);
        cn.Open();

        SqlCommand cmd = new SqlCommand("social_media_list", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader dr = cmd.ExecuteReader();

        media.Text = "";

        bool af = false;
        while (dr.Read())
        {
            af = true;
            DateTime date = Convert.ToDateTime(dr[2].ToString());
            string description = dr[3].ToString();
            string file = HttpContext.Current.Request.ApplicationPath + "/upload/media/" + dr[1].ToString() + dr[0].ToString();

            media.Text += "<tr><td>";
            media.Text += "<a href=";
            media.Text += file;
            media.Text += ">appraisal.pdf</a>";
            media.Text += "</td><td>";
            media.Text += description;
            media.Text += "</td><td>";
            media.Text += date.ToShortDateString();
            media.Text += "</td></tr>";
        }
        if (af == false) media.Text += "<tr><td>No media files available.</td></td><td></td><td></tr>";
    }

    public void uploadappraisal_Click(object sender, System.EventArgs e)
    {
        if (CheckValidAppraisalInputs(FileUploadAppraisal))
        {
            object propertyID = Master.PropertyID;
            SaveAppraisal(propertyID, FileUploadAppraisal);
        }
    }

    public void uploadmedia_Click(object sender, System.EventArgs e)
    {
        if (CheckValidMediaInputs(FileUploadMedia))
        {
            object propertyID = Master.PropertyID;
            SaveMedia(propertyID, FileUploadMedia);
        }
    }

    private void mbox(string p)
    {
        throw new NotImplementedException();
    }

    private bool CheckValidAppraisalInputs(FileUpload uploadedFile)
    {
        string filePath = uploadedFile.PostedFile.FileName.Trim();

        try
        {
            decimal appraisalValue = Convert.ToDecimal(Value.Value);
        }
        catch (Exception)
        {
            return false;
        }

        try
        {
            DateTime dateOfAppraisal = Convert.ToDateTime(Date.Value);
        }
        catch (Exception)
        {
            return false;
        }

        if (String.IsNullOrEmpty(filePath) || uploadedFile.PostedFile.ContentLength == 0)
        {
            return false;
        }

        return true;
    }

    private bool CheckValidMediaInputs(FileUpload uploadedFile)
    {
        string filePath = uploadedFile.PostedFile.FileName.Trim();

        try
        {
            string description = (Description.Value).ToString();
        }
        catch (Exception)
        {
            return false;
        }

        if (String.IsNullOrEmpty(filePath) || uploadedFile.PostedFile.ContentLength == 0)
        {
            return false;
        }

        return true;
    }

    private void SaveAppraisal(object propertyID, FileUpload file)
    {
        if (file.PostedFile == null || file.PostedFile.FileName.Trim().Length == 0 || file.PostedFile.ContentLength == 0)
            return;

        string sUpDir = Request.MapPath(YAF.Classes.Config.UploadDir);
        string filename = file.PostedFile.FileName;

        int pos = filename.LastIndexOfAny(new char[] { '/', '\\' });
        if (pos >= 0) filename = filename.Substring(pos + 1);

        // filename can be only 255 characters long (due to table column)
        if (filename.Length > 255) filename = filename.Substring(filename.Length - 255);

        decimal appraisalValue = Convert.ToDecimal(Value.Value);
        DateTime dateOfAppraisal = Convert.ToDateTime(Date.Value);

        SqlConnection cn = new SqlConnection(YAF.Classes.Config.ConnectionString);
        cn.Open();

        SqlCommand usercmd = new SqlCommand("social_userid_get", cn);
        usercmd.CommandType = CommandType.StoredProcedure;

        usercmd.Parameters.Add("@userName", SqlDbType.NVarChar);
        usercmd.Parameters["@userName"].Value = HttpContext.Current.User.Identity.Name.ToString();

        SqlDataReader userdr = usercmd.ExecuteReader();

        if (userdr.Read())
        {
            int userID = Convert.ToInt32(userdr[0]);
            userdr.Close();

            SqlCommand cmd = new SqlCommand("social_appraisals_save", cn);
            cmd.CommandType = CommandType.StoredProcedure;

            string dir = sUpDir + "appraisals/";
            file.PostedFile.SaveAs(String.Format("{0}{1}{2}", dir, propertyID, filename));

            byte[] fileData = null;
            cmd.Parameters.AddWithValue("PropertyID", propertyID);
            cmd.Parameters.AddWithValue("FileName", filename);
            cmd.Parameters.AddWithValue("Bytes", file.PostedFile.ContentLength);
            cmd.Parameters.AddWithValue("ContentType", file.PostedFile.ContentType);
            cmd.Parameters.AddWithValue("FileData", fileData);
            cmd.Parameters.AddWithValue("AppraisalValue", appraisalValue);
            cmd.Parameters.AddWithValue("DateOfAppraisal", dateOfAppraisal);
            cmd.Parameters.AddWithValue("UserID", userID);
            cmd.ExecuteNonQuery();
        }
        object sender = null;
        EventArgs e = null;
        Page_Load(sender, e);
    }

    private void SaveMedia(object propertyID, FileUpload file)
    {
        if (file.PostedFile == null || file.PostedFile.FileName.Trim().Length == 0 || file.PostedFile.ContentLength == 0)
            return;

        string sUpDir = Request.MapPath(YAF.Classes.Config.UploadDir);
        string filename = file.PostedFile.FileName;

        int pos = filename.LastIndexOfAny(new char[] { '/', '\\' });
        if (pos >= 0) filename = filename.Substring(pos + 1);

        // filename can be only 255 characters long (due to table column)
        if (filename.Length > 255) filename = filename.Substring(filename.Length - 255);

        string description = (Description.Value).ToString();
        DateTime datePosted = DateTime.Now;

        SqlConnection cn = new SqlConnection(YAF.Classes.Config.ConnectionString);
        cn.Open();

        SqlCommand usercmd = new SqlCommand("social_userid_get", cn);
        usercmd.CommandType = CommandType.StoredProcedure;

        usercmd.Parameters.Add("@userName", SqlDbType.NVarChar);
        usercmd.Parameters["@userName"].Value = HttpContext.Current.User.Identity.Name.ToString();

        SqlDataReader userdr = usercmd.ExecuteReader();

        if (userdr.Read())
        {
            int userID = Convert.ToInt32(userdr[0]);
            userdr.Close();

            SqlCommand cmd = new SqlCommand("social_media_save", cn);
            cmd.CommandType = CommandType.StoredProcedure;

            string dir = sUpDir + "media/";
            file.PostedFile.SaveAs(String.Format("{0}{1}{2}", dir, propertyID, filename));

            byte[] fileData = null;
            cmd.Parameters.AddWithValue("PropertyID", propertyID);
            cmd.Parameters.AddWithValue("FileName", filename);
            cmd.Parameters.AddWithValue("Bytes", file.PostedFile.ContentLength);
            cmd.Parameters.AddWithValue("ContentType", file.PostedFile.ContentType);
            cmd.Parameters.AddWithValue("FileData", fileData);
            cmd.Parameters.AddWithValue("Description", description);
            cmd.Parameters.AddWithValue("DatePosted", datePosted);
            cmd.Parameters.AddWithValue("UserID", userID);
            cmd.ExecuteNonQuery();
        }
        object sender = null;
        EventArgs e = null;
        Page_Load(sender, e);
    }

}
